package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.mapper.AuthorMapper;
import com.heima.article.service.ApArticleService;
import com.heima.common.constants.article.ArticleConstants;
import com.heima.common.constants.message.NewsUpOrDownConstants;
import com.heima.common.exception.CustException;
import com.heima.feigns.AdminFeign;
import com.heima.feigns.WemediaFeign;
import com.heima.model.admin.pojos.AdChannel;
import com.heima.model.article.dtos.ArticleHomeDTO;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmNews;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;


@Service
@Slf4j
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {

    @Autowired
    WemediaFeign wemediaFeign;


    /**
     * 新增发布文章
     *
     * @param newsId Wmnews的Id  为了查询news文章
     */

    @Autowired
    GeneratePageServiceImpl generatePageService;


    @Autowired
    RabbitTemplate rabbitTemplate;
    @Override
    @Transactional
    public void publishArticle(Integer newsId) {
        //1. 查询并校验文章数据
        WmNews wmNews = getWmNews(newsId);
        //2 . 将Wmnews封装成ap article对象
        ApArticle apArticle = getApArticle(wmNews);
        //3 . 保存或修改ap   article
        saveOrUpdateArticle(apArticle);
        //4 . 保存关联配置信息，和内文章内容
        saveConfigAndContent(wmNews, apArticle);
        //5. 页面静态化 生成HTML文件
        generatePageService.generateArticlePage(wmNews.getContent(), apArticle);
        //6 . 更新Wmnews的文章状态为9
        updateWmNews(wmNews, apArticle);
        //7 . 通知es索引库添加文章
        rabbitTemplate.convertAndSend(NewsUpOrDownConstants.NEWS_UP_FOR_ES_QUEUE,apArticle.getId());
        log.info("文章发布成功，并发送索引库更新通知   文章id: {}",apArticle.getId());

    }


    /**
     * 根据参数加载文章列表
     *
     * @param loadtype 1为加载更多  2为加载最新
     * @param dto
     * @return
     */


    @Value("${file.oss.web-site}")
    String webSite;

    @Value("${file.minio.readpath}")
    String readpath;


    @Autowired
    ApArticleMapper apArticleMapper;


    @Override
    public ResponseResult load(Short loadtype, ArticleHomeDTO dto) {
        //1 . 校验参数， size ， type ， 频道
        //size
        Integer size = dto.getSize();
        if (size == null) {
            dto.setSize(10);
        }
        //type
        if (!loadtype.equals(ArticleConstants.LOADTYPE_LOAD_MORE)
                && !loadtype.equals(ArticleConstants.LOADTYPE_LOAD_NEW)) {
            loadtype = ArticleConstants.LOADTYPE_LOAD_MORE;
        }
        //time
        if (dto.getMaxBehotTime() == null) {
            dto.setMaxBehotTime(new Date());
        }
        if (dto.getMinBehotTime() == null) {
            dto.setMinBehotTime(new Date());
        }
        //频道
        if (StringUtils.isBlank(dto.getTag())) {
            dto.setTag(ArticleConstants.DEFAULT_TAG);
        }
        //2 . 调用articlemapper查询
        List<ApArticle> apArticles = apArticleMapper.loadArticleList(dto, loadtype);

        //3 . 将文章静态页加前缀
        for (ApArticle apArticle : apArticles) {
            apArticle.setStaticUrl(readpath + apArticle.getStaticUrl());
        }

        ResponseResult responseResult = ResponseResult.okResult(apArticles);
        responseResult.setHost(webSite);
        return responseResult;

    }

    @Autowired
    StringRedisTemplate redisTemplate;

    //更新的显示方法
    @Override
    public ResponseResult load2(Short loadtypeLoadMore, ArticleHomeDTO dto, boolean firstPage) {
        if (firstPage) {
            String hotArticleJson = redisTemplate.opsForValue().get(ArticleConstants.HOT_ARTICLE_FIRST_PAGE + dto.getTag());
            if (StringUtils.isNotBlank(hotArticleJson)){
                List<ApArticle> apArticles = JSON.parseArray(hotArticleJson, ApArticle.class);
                for (ApArticle apArticle : apArticles) {
                    apArticle.setStaticUrl(readpath +apArticle.getStaticUrl());
                }
                ResponseResult responseResult = ResponseResult.okResult(apArticles);
                responseResult.setHost(webSite);
                return responseResult;
            }
        }
        return load(loadtypeLoadMore, dto);
    }


    /**
     * 6 . 更新Wmnews的文章状态为9
     *
     * @param wmNews
     * @param apArticle
     */
    private void updateWmNews(WmNews wmNews, ApArticle apArticle) {
        wmNews.setStatus(WmNews.Status.PUBLISHED.getCode());//状态改为发布状态
        wmNews.setArticleId(apArticle.getId());
        ResponseResult responseResult = wemediaFeign.updateWmNews(wmNews);
        if (!responseResult.checkCode()) {
            log.error("远程调用状态修改失败");
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR, "远程调用状态修改异常");
        }
    }

    /**
     * 4 . 保存关联配置信息，和内文章内容
     *
     * @param wmNews
     * @param apArticle
     */
    private void saveConfigAndContent(WmNews wmNews, ApArticle apArticle) {
        // 4.1 先保存配置信息
        ApArticleConfig config = new ApArticleConfig();
        config.setArticleId(apArticle.getId());
        config.setIsComment(true);
        config.setIsForward(true);
        config.setIsDown(false);
        config.setIsDelete(false);
        apArticleConfigMapper.insert(config);

        ApArticleContent content = new ApArticleContent();
        content.setArticleId(apArticle.getId());
        content.setContent(wmNews.getContent());
        apArticleContentMapper.insert(content);
    }


    @Autowired
    ApArticleConfigMapper apArticleConfigMapper;

    @Autowired
    ApArticleContentMapper apArticleContentMapper;

    /**
     * //3 . 保存或修改ap article 存入数据到表中
     *
     * @param apArticle
     */
    private void saveOrUpdateArticle(ApArticle apArticle) {
        //判断文章的id是否存在
        if (apArticle.getId() == null) {
            //如果不存在就保存(重新设置点赞量，阅读量，收藏量，评论量)
            apArticle.setCollection(0);//收藏量
            apArticle.setLikes(0);//点赞量
            apArticle.setViews(0);//阅读量
            apArticle.setComment(0);//评论量
            save(apArticle);
        } else {
            //存在。就修改article文章的数据
            //根据id先查一下文章是否真的存在
            ApArticle oldArticle = getById(apArticle.getId());
            if (oldArticle == null) {
                log.error("article文章通过id查询，但是数据为空");
                CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "article文章通过id查询，但是数据为空");
            }
            updateById(apArticle);
            //一定要删除之前那关联的旧的配置信息
            apArticleConfigMapper.delete(Wrappers.<ApArticleConfig>lambdaQuery()
                    .eq(ApArticleConfig::getArticleId, apArticle.getId()));
            //一定要删除之前那关联的旧的内容信息
            apArticleContentMapper.delete(Wrappers.<ApArticleContent>lambdaQuery()
                    .eq(ApArticleContent::getArticleId, apArticle.getId()));
        }
    }


    @Autowired
    AuthorMapper authorMapper;
    @Autowired
    AdminFeign adminFeign;

    // 将Wmnews封装成ap article对象的方法
    private ApArticle getApArticle(WmNews wmNews) {
        //2.1先创建article对象，将wmNews中的属性拷贝到article中
        ApArticle apArticle = new ApArticle();
        BeanUtils.copyProperties(wmNews, apArticle);
        //2.2补全未拷贝属性（articleId  flag layout）
        apArticle.setId(wmNews.getArticleId());
        apArticle.setFlag((byte) 0);
        apArticle.setLayout(wmNews.getType());//布局类型
        //2.3补全作者信息 , 频道信息，
        ApAuthor author = authorMapper.selectOne(Wrappers.<ApAuthor>lambdaQuery()
                .eq(ApAuthor::getWmUserId, wmNews.getUserId()));
        if (author == null) {//补全作者信息
            log.error("补全作者信息出错，查询出作者信息为null");
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "作者信息不存在");
        }
        apArticle.setAuthorId(Long.valueOf(author.getId()));
        apArticle.setAuthorName(author.getName());

        //补全频道信息
        ResponseResult<AdChannel> channelResult = adminFeign.findOne(wmNews.getChannelId());

        if (!channelResult.checkCode()) {
            log.error("远程调用频道失败");
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR, "远程调用频道异常");
        }
        AdChannel channel = channelResult.getData();
        if (channel == null) {
            log.error("补全频道信息出错，查询出频道信息为null");
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "补全频道信息出错，查询出频道信息为null");
        }
        apArticle.setChannelName(channel.getName());
        //2.4返回分装好的频道，作者的ap adticle
        return apArticle;
    }


    //1.1 通过id调用feign接口，远程查询文章内容
    private WmNews getWmNews(Integer newsId) {
        //1.1.1查询文章
        ResponseResult<WmNews> newsResullt = wemediaFeign.findWmNewsById(newsId);
        if (!newsResullt.checkCode()) {
            log.error("远程调用失败");
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR, "远程调用异常");
        }
        //1.1.2校验文章是否存在
        WmNews wmNews = newsResullt.getData();
        if (wmNews == null) {
            log.error("远程调用的news文章信息为空");
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "文章信息不存在");
        }
        //1.1.3校验文章的状态，是否为4或者8
        short status = wmNews.getStatus().shortValue();
        if (WmNews.Status.ADMIN_SUCCESS.getCode() != status
                && WmNews.Status.SUCCESS.getCode() != status) {
            log.error("状态不为 4 和 8 ");
            CustException.cust(AppHttpCodeEnum.LOGIN_STATUS_ERROR, "文章的状态是未审核的状态");
        }
        return wmNews;
    }


}